import { MockMCPClient } from './quick-start';

async function mockMultiRoundExample() {
  console.log('=== Mock Multi-Round Tool Calling Example ===');
  
  const mockClient = new MockMCPClient({
    serverUrl: 'ws://localhost:9999/mock',
    timeout: 30000,
    retryCount: 1
  });
  
  try {
    await mockClient.connect();
    console.log('Mock client connected for multi-round demo\n');
    
    // 模拟多轮工具调用的场景
    console.log('🔄 Multi-Round Tool Calling Demonstration');
    console.log('='.repeat(50));
    
    // Round 1: 获取天气
    console.log('\n📍 Round 1: Getting weather data...');
    const weatherResult = await mockClient.callTool('get_weather', { location: 'Beijing' });
    console.log('Weather Result:', weatherResult);
    
    // Round 2: 温度转换
    console.log('\n📍 Round 2: Converting temperature...');
    const tempConversion = await mockClient.callTool('calculate', { expression: '25 * 9/5 + 32' });
    console.log('Temperature Conversion:', tempConversion);
    
    // Round 3: 计算湿度相关指标
    console.log('\n📍 Round 3: Calculating humidity comfort index...');
    const humidityCalc = await mockClient.callTool('calculate', { expression: '47 * 0.5 + 25' });
    console.log('Humidity Index:', humidityCalc);
    
    console.log('\n✅ Multi-round tool calling completed successfully!');
    
    // 演示逻辑流程
    console.log('\n📋 Logic Flow Demonstration:');
    console.log('1. User: "分析北京天气并提供建议"');
    console.log('2. LLM: calls get_weather(Beijing)');
    console.log('3. Agent: executes → gets weather data');
    console.log('4. LLM: analyzes → needs temperature conversion');
    console.log('5. LLM: calls calculate(25°C to °F)');
    console.log('6. Agent: executes → gets converted temperature');
    console.log('7. LLM: analyzes → needs humidity index');
    console.log('8. LLM: calls calculate(humidity formula)');
    console.log('9. Agent: executes → gets comfort index');
    console.log('10. LLM: has all data → generates comprehensive response');
    
    console.log('\n💡 Key Benefits of Multi-Round Tool Calling:');
    console.log('• Complex task breakdown into sequential steps');
    console.log('• Data collection → analysis → action workflow');
    console.log('• Dynamic decision making based on results');
    console.log('• Error handling at each step');
    console.log('• Context accumulation across rounds');
    
  } catch (error) {
    console.error('Mock multi-round example failed:', error);
  } finally {
    await mockClient.disconnect();
  }
}

// 详细的多轮工具调用逻辑说明
function detailedMultiRoundExplanation() {
  console.log(`
🔍 Detailed Multi-Round Tool Calling Logic:

📝 Code Flow in generateResponseWithToolResults():

1. Entry Point
   └─ generateResponseWithToolResults() called
     └─ Delegates to handleMultiRoundToolCalls()

2. handleMultiRoundToolCalls() Structure
   ┌─────────────────────────────────────────┐
   │ while (currentRound < maxRounds) {      │
   │   currentRound++;                        │
   │   build messages from history;           │
   │   call LLM with tools available;         │
   │   if (LLM wants more tools) {             │
   │     execute tools;                       │
   │     add to history;                      │
   │     continue; // Next round              │
   │   } else {                               │
   │     return final response;               │
   │   }                                      │
   │ }                                        │
   └─────────────────────────────────────────┘

3. Message Construction for Each Round
   [
     {role: "system", content: "You are a helpful assistant..."},
     {role: "user", content: originalMessage},
     {role: "assistant", content: "Round 1 response"},
     {role: "system", content: "Tool results Round 1..."},
     {role: "assistant", content: "Round 2 response"},
     {role: "system", content: "Tool results Round 2..."},
     ... // Continues for each round
   ]

4. Tool Call Detection Logic
   if (response.tool_calls && response.tool_calls.length > 0) {
     // Execute tools and continue to next round
   } else {
     // Return final response
   }

5. Safety Mechanisms
   • Max rounds (5) prevents infinite loops
   • Error handling stops on tool failures  
   • Complete conversation history maintained
   • Progress logging for debugging

🛠️ Implementation Details:

• Tool Execution: executeToolCalls() in parallel
• Result Storage: ToolCallResult[] with success/failure status
• History Management: Array of conversation turns
• Context Preservation: All previous results sent to LLM
• Decision Logic: LLM decides when to stop calling tools

🎯 Real-World Applications:

1. Travel Planning
   → Weather check → Flight search → Hotel booking → 
   → Attraction lookup → Itinerary generation

2. Data Analysis  
   → Data collection → Cleaning → Analysis → 
   → Visualization → Report generation

3. Customer Support
   → Issue identification → Knowledge search → 
   → Solution recommendation → Follow-up scheduling

4. Research Tasks
   → Literature search → Data extraction → 
   → Analysis → Summary generation → Citation formatting
`);
}

export { mockMultiRoundExample, detailedMultiRoundExplanation };

if (require.main === module) {
  detailedMultiRoundExplanation();
  mockMultiRoundExample().catch(console.error);
}